#pragma once

#include <string>
#include <vector>
#include <fstream>
#include <unordered_map>
#include <unordered_set>
#include <sstream>
#include <unordered_set>

#include <jsoncpp/json/json.h>

#include "../../Utility/Log/Log.hpp"
#include "../../Utility/Static/Algorithmf.hpp"
#include "../../Utility/Data/NavMessageData/GNSSMesData.hpp"

namespace ns_GNSSMesInput
{
    using namespace ns_Util;
    using namespace ns_Log;
    using namespace ns_GNSSMesData;

    class GNSSMesPackager
    {
        public:
        GNSSMesPackager()
        {}

        public:
        static int PackgeHeader(const std::string& fileName,const std::vector<GNSSMesHeader::Ptr>& input)
        {
            for(auto e:input)
            {
                if(e==nullptr)
                    continue;

                GNSSType gnssType = e->gnssType;
                std::string filePath = PathUtil::Header(fileName,gnssType);
                
                std::string json;
                if(e->Encode(&json))
                {
                    FileUtil::WriteToFile(filePath,json);
                }
            }

            return 0;
        }

        static int PackgeRecord(const std::string& fileName,
            const std::vector<GNSSMesRecord::Ptr>& input)
        {
            std::unordered_map<GNSSType,std::unordered_map<int,std::vector<GNSSMesRecord::Ptr>>> hash;

            Json::Reader reader;

            for(auto e:input)
            {
                if(e==nullptr)
                    continue;

                GNSSType type = e->gnssType;
                int serial = e->serial;

                hash[type][serial].push_back(e);
            }

            for(const auto& e:hash)
            {
                GNSSType type = e.first;
                for(const auto& v:e.second)
                {
                    int serial = v.first;
                    const auto& records = v.second;

                    int n =records.size();
                    Json::Value value;
                    value["Size"] = n;
                    for(int i =0;i<n;i++)
                    {
                        std::string recordJson;
                        records[i]->Encode(&recordJson);
                        Json::Value recordValue;
                        reader.parse(recordJson,recordValue);

                        value["Content"][i] = recordValue;
                    }

                    std::string json;
                    Json::FastWriter writer;
                    json = writer.write(value);

                    std::string path = PathUtil::Record(fileName,type,serial);
                    FileUtil::WriteToFile(path,json);
                }
            }

            return 0;
        }
    };
}
